<?php
namespace app\api\controller\salesman;

use think\Request;
use app\common\model\contract\ProductContract;
use think\Db;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\api\controller\Base;
use think\facade\Env;
use app\api\controller\Pub;

class Contract extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('305005'); // 合同管理权限
    }

    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    // 合同列表
    public function contractList(Request $request)
    {
        $pub = new Pub();
        $user_id = $pub->userid();
        $role = Db::name('user')->where('UserId', $user_id)->value('Role');
        $customer_ids = [];
        if ($role == 305) {
            // 销售管理员
            $group_id = Db::name('user_group')->where('user_id', $user_id)->value('group_id');
            $emp_ids = Db::name('user_group')->where('group_id', $group_id)->column('user_id');
            $customer_ids = Db::name('user_customer')->whereIn('user_id', $emp_ids)->column('customer_id');
        } elseif ($role == 306) {
            // 销售员工，
            $customer_ids = Db::name('user_customer')->where('user_id', $user_id)->column('customer_id');
        } 
        if (empty($customer_ids)) {
            return json(['code'=>1, 'msg'=>'success', 'data'=>[]]);
        }

        $list = ProductContract::whereIn('customer_id', $customer_ids)->order('create_time desc')->select();
        
        return json(['code'=>1, 'msg'=>'success', 'data'=>$list]);
    }

    // 合同添加
    public function contractAdd(Request $request)
    {
        $pub = new Pub();
        $user_id = $pub->userid();
        $res=$this->upimg();
        $res=(array)json_decode($res);
        $data = $request->post();
        if (empty($data['customer_id']) || empty($data['name']) || empty($data['remark']) ) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $contract = new ProductContract();
        $contract->customer_id = $data['customer_id'];
        $contract->name = $data['name'];
        $contract->remark = $data['remark'];
        $contract->img_url = $res['data'];
        $contract->payment_time = $data['payment_time'] ?? null;
        $contract->payment_status = $data['payment_status'] ?? 0;
        $contract->cost = $data['cost'] ?? null;
        $contract->create_time = time();
        $contract->update_time = time();
        $contract->save();
        return json(['code'=>1, 'msg'=>'添加成功']);
    }

    // 合同修改
    public function contractEdit(Request $request)
    {
        $file = request()->file('img');

        if($file){
            $res=$this->upimg();
            $res=(array)json_decode($res);
            $img_url=$res['data'];
        }
        $data = $request->post();
        
        if (empty($data['id'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $contract = ProductContract::get($data['id']);
        if (!$contract) {
            return json(['code'=>0, 'msg'=>'合同不存在']);
        }
        //删除原合同文件(???)有问题?????
        if($file){
            if(is_file($contract->img_url)){
                unlink($contract->img_url);
            }
            $contract->img_url=$img_url;
        }

        $contract->name  =$data['name']  ?? $contract->name;
        $contract->remark = $data['remark'] ?? $contract->remark;
        $contract->payment_status = $data['payment_status'] ?? $contract->payment_status;
        $contract->cost = $data['cost'] ?? $contract->cost;
        $contract->payment_time = $data['payment_time'] ?? $contract->payment_time;
        $contract->update_time = time();
        $contract->save();
        return json(['code'=>1, 'msg'=>'修改成功']);
    }

    //根据合同查看具体的订单；
    public function orderDetail(Request $request)
    {
        $contract_id=$request->post('contract_id');
        if (!$contract_id) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $orders = Db::name('contract_order')->whereIn('contract_id', $contract_id)->field('id,device_id,accessories_id,track_number,status,create_time,update_time')->select();
        foreach ($orders as &$order) {
            $order['device'] = Db::name('device')->whereIn('id', explode(',', $order['device_id']))->field('id,name')->select();
            $order['accessories'] = isset($order['accessories_id']) ? Db::name('accessories')->whereIn('id', explode(',', $order['accessories_id']))->select() : [];
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['update_time'] = date('Y-m-d H:i:s', $order['update_time']);
 
            // 按device_id分组配件
            $accessoriesByDevice = [];
            foreach ($order['accessories'] as $acc) {
                $accessoriesByDevice[$acc['device_id']][] = $acc;
            }
            // 给每个设备加上accessories字段
            foreach ($order['device'] as &$dev) {
                $dev['accessories'] = isset($accessoriesByDevice[$dev['id']]) ? $accessoriesByDevice[$dev['id']] : [];
            }
            //删除不必要的字段
            unset($dev);
            unset($order['accessories']);
            unset($order['device_id']);
            unset($order['accessories_id']);
        }
        return json(['code'=>1, 'msg'=>'success', 'data'=>$orders]);
    }

    //上传合同凭证
    public function upimg(){
		$type = empty(input('type'))?'other':input('type');
		if(!$type=='hawa'||!$type=='buss'||!$type=='acco' || !$type=='product'){
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status'=>'error','data'=>$e->getMessage()]);
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\countract\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>SERVERURL.'static/upimg/countract/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}

         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}
} 